package de.pharmacontrol.psa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import de.pharmacontrol.pilot.entities.Line;
import de.pharmacontrol.pilot.entities.LogEntry;
import de.pharmacontrol.pilot.entities.User;
import de.pharmacontrol.psa.parameters.LogEntryQueryParameters;

public class LogEntryProvider implements PagedDataProvider<LogEntry, LogEntryQueryParameters> {

	@PersistenceContext(unitName = "pilot")
	protected EntityManager em;

	private final int pageSize;
	private final LogEntryQueryParameters queryCriteria;

	public LogEntryProvider(int pageSize, LogEntryQueryParameters queryCriteria) {
		this.pageSize = pageSize;
		this.queryCriteria = queryCriteria;
	}

	public List<LogEntry> getAllLogEntries(User user, Line line) {
		// optional query parameters: can be null
		LogEntryQueryParameters params = new LogEntryQueryParameters();
		params.setUser(user);
		params.setLine(line);
		return new PagedList<LogEntry, LogEntryQueryParameters>(this, params);
	}

	@SuppressWarnings("unchecked")
	public List<LogEntry> provide(int page, LogEntryQueryParameters queryCriteria) {
		Query query = em.createQuery("select l from LogEntry l where l.line = :line and l.user = :user", LogEntry.class);
		query.setParameter("user", queryCriteria.getUser());
		query.setParameter("line", queryCriteria.getLine());
		// JPA's paging mechanism
		query.setFirstResult(pageSize * page);
		query.setMaxResults(pageSize);
		return (List<LogEntry>) query.getResultList();
	}

	/**
	 * @see PagedDataProvider#getDataSize()
	 */
	public int getDataSize() {
		Query countQuery = em.createQuery("select COUNT(l) from LogEntry l where l.line = :line and l.user = :user", LogEntry.class);
		countQuery.setParameter("user", queryCriteria.getUser());
		countQuery.setParameter("line", queryCriteria.getLine());
		return ((Long) countQuery.getSingleResult()).intValue();
	}

	/**
	 * @see PagedDataProvider#provide()
	 */
	public int getPageSize() {
		return pageSize;
	}

}
